package rabbitmq.direct;

import com.rabbitmq.client.*;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 创建连接⼯⼚
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost(Constants.HOST);//ip 默认值localhost
        factory.setPort(Constants.PORT); //默认值5672
        factory.setVirtualHost(Constants.VIRTUAL_HOST);//虚拟机名称, 默认 /
        factory.setUsername(Constants.USER_NAME);//⽤⼾名,默认guest
        factory.setPassword(Constants.PASSWORD);//密码, 默认guest
        //3. 创建连接Connection
        Connection connection = factory.newConnection();
        //4. 创建channel通道
        Channel channel = connection.createChannel();
        //5. 声明队列
        channel.queueDeclare(Constants.DIRECT_QUEUE1,true,false,false,null);
        // 6. 接收消息, 并消费
        DefaultConsumer consumer = new DefaultConsumer(channel) {    // 这段代码是消费的逻辑
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息: " + new String(body));
            }
        };
        channel.basicConsume(Constants.DIRECT_QUEUE1, true, consumer);     // 消费
    }
}
